package cn.idongjia.live.vcload;

import cn.idongjia.live.pojo.AuthLive;

import java.security.MessageDigest;

/**
 * 网易云加密参数生成
 * Created by wuqiang on 16/3/31.
 */
public class CheckSumBuilder {

    private static final char[] HEX_DIGITS =
            {'0', '1', '2', '3', '4', '5', '6', '7',
                    '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    private static final int DIGITAL_OFFSET = 4;
    private static final byte CONJUNCTION = 0x0f; //定义与运算常量

    /**
     * 计算云服务器需要参数:服务器认证需要,SHA1(AppSecret+Nonce+CurTime),16进制字符小写
     * 对参数进行安全哈希算法（Secure Hash Algorithm）加密
     *
     * @param appSecret
     * @param nonce     随机数（随机数，最大长度128个字符）
     * @param curTime   当前UTC时间戳
     * @return
     */
    public static String getCheckSum(String appSecret, String nonce, String curTime) {
        return encode("sha1", appSecret + nonce + curTime);
    }

    /**
     * 自动生成网易云频道名称
     *
     * @param authLive 授权管理员授权信息
     * @return 生成频道名称只需要授权
     */
    public static String authChannelName(final AuthLive authLive) {
        return "aid" + authLive.getId().toString() + "-" + System.currentTimeMillis();
    }

    /**
     * 哈希加密
     *
     * @param algorithm
     * @param value
     * @return 加密结果
     */
    private static String encode(String algorithm, String value) {
        if (value == null) {
            return null;
        }
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            messageDigest.update(value.getBytes());
            return getFormattedText(messageDigest.digest());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Hex加密
     *
     * @param bytes
     * @return
     */
    private static String getFormattedText(byte[] bytes) {
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        for (int j = 0; j < len; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >> DIGITAL_OFFSET & CONJUNCTION)]);
            buf.append(HEX_DIGITS[bytes[j] & CONJUNCTION]);
        }
        return buf.toString();
    }

}
